package com.bread.tliaswebmanagement.aop;

import com.bread.tliaswebmanagement.mapper.OperateLogMapper;
import com.bread.tliaswebmanagement.pojo.OperateLog;
import com.bread.tliaswebmanagement.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;
    
    @Around("@annotation(com.bread.tliaswebmanagement.anno.Log)")
    public Object recordOperateLog(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            // 执行目标方法
            result = joinPoint.proceed();
            return result;
        } finally {
            try {
                // 计算方法耗时
                long costTime = System.currentTimeMillis() - startTime;
                
                // 获取操作人信息（需要根据具体系统实现）
                Integer operateEmpId = getCurrentOperateEmpId();
                
                // 获取方法签名信息
                String className = joinPoint.getTarget().getClass().getName();
                String methodName = joinPoint.getSignature().getName();

                //获取参数
                Object[] args = joinPoint.getArgs();

                // 构建日志对象
                OperateLog operateLog = new OperateLog();
                operateLog.setOperateEmpId(operateEmpId);
                operateLog.setOperateTime(LocalDateTime.now());
                operateLog.setClassName(className);
                operateLog.setMethodName(methodName);
                operateLog.setMethodParams(Arrays.toString(args));
                operateLog.setReturnValue(result != null ? result.toString() : "void");
                operateLog.setCostTime(costTime);

                // 保存日志
                operateLogMapper.insert(operateLog);
                log.info("操作日志记录成功:{}", operateLog);
            } catch (Exception e) {
                // 日志记录异常不应影响主流程
                log.error("操作日志记录失败", e);
            }
        }
    }

    // 获取当前操作人ID（需要根据具体系统安全框架实现）
    private Integer getCurrentOperateEmpId() {
         return CurrentHolder.getCurrentId();
    }
}